

#import "XTXXitongViewController.h"
#import "MJRefresh.h"
#import "SDAutoLayout.h"
#import "XTXXitongCell.h"
#define SCREEN_WIDTH ([[UIScreen mainScreen] bounds].size.width)

@interface XTXXitongViewController ()<UITableViewDelegate,UITableViewDataSource>{
    CGFloat temWidth;
    MBProgressHUD *progreHud;
    CGFloat temHeight;
    NSInteger pageCount;
    NSString *strTemp;
}

@property (nonatomic,strong) UIImageView *wuneirongImageView;
@property (nonatomic,strong) UILabel *wuneirongLabel;
@property (nonatomic,strong) NSMutableArray *xitongArr;
@property (nonatomic,strong) MJRefreshAutoStateFooter *refreFooter;
@property (nonatomic,strong) UITableView *tableView;

@end

@implementation XTXXitongViewController

-(UIImageView *)wuneirongImageView{
    if (!_wuneirongImageView) {
        _wuneirongImageView = [UIImageView new];
        _wuneirongImageView.image = [UIImage imageNamed:@"无内容图片"];
    }
    return _wuneirongImageView;
}
- (void)writeJsonObject:(id)jsonObject IntoDocumentsFile:(NSString *)fileName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *DocumentsPath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    
    NSString *JsonPath = [DocumentsPath stringByAppendingPathComponent:fileName];
    
    [self writeJsonObject:jsonObject intoFile:JsonPath];
}
-(UILabel *)wuneirongLabel{
    if (!_wuneirongLabel) {
        _wuneirongLabel = [UILabel new];
        _wuneirongLabel.textColor = XZRGB(0xc8c8c8);
        _wuneirongLabel.font = [UIFont systemFontOfSize:14];
        _wuneirongLabel.textAlignment = NSTextAlignmentCenter;
        _wuneirongLabel.text = @"暂时没有任何系统通知";
    }
    return _wuneirongLabel;
}
-(void)writeJsonObject:(id)object intoFile:(NSString *)filePath {
    if (filePath.length==0) {
        return;
    }
    NSError *error;
    //1.创建输出流对象
    NSOutputStream *outpusStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
    //2.打开
    [outpusStream open];
    //3.将json内容写入文件
//    [NSJSONSerialization writeJSONObject:object toStream:outpusStream options:NSJSONWritingPrettyPrinted error:&error];
    if (error) {
        NSLog(@"写入文件失败: %@",error.description);
    }else{
        NSLog(@"写入文件成功: %@",filePath);
    }
    //4.关闭
    [outpusStream close];
}

-(void)fanhuishangyigejiemian
{
    [self writeJsonObject:nil IntoDocumentsFile:nil];
    [self readObjectFromFile:nil];
    [self.navigationController popViewControllerAnimated:YES];
}
-(id)readObjectFromFile:(NSString *)filePath {
    if (filePath.length==0) {
        return nil;
    }
    NSError *error;
    //1.创建输入流对象
    NSInputStream *inputStream = [[NSInputStream alloc] initWithFileAtPath:filePath];
    [inputStream open];
    //2.将json文件的内容读写到NSDictionary
    id jsonObject = [NSJSONSerialization JSONObjectWithStream:inputStream options:NSJSONReadingMutableContainers error:&error];
    
    if (error) {
        NSLog(@"读取文件失败: %@",error.description);
    }else{
        NSLog(@"读取文件成功: %@",filePath);
    }
    [inputStream close];
    return jsonObject;
}
-(void)loadTabItem
{
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    
    UIBarButtonItem *tortureapothegm = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"后退按钮"] landscapeImagePhone:[UIImage imageNamed:@"后退按钮"] style:UIBarButtonItemStylePlain target:self action:@selector(fanhuishangyigejiemian)];
    tortureapothegm.tintColor = [UIColor blackColor];
    self.navigationItem.leftBarButtonItem = tortureapothegm;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"清空消息" style:0 target:self action:@selector(clearMeaage)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor blackColor];
    
}

-(void)clearMeaage
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"user_id"] = XTXGongTool.share.useMode.id;
    WeakSelf
    [XTXNetworking networkingDelUseXitongMsgdewangluoqingqiu:dict.copy completionHandler:^(NSDictionary * _Nonnull dict) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([dict[@"code"] integerValue] == 1) {
                [weakSelf.xitongArr removeAllObjects];
                [weakSelf.tableView reloadData];
                weakSelf.wuneirongImageView.hidden = NO;
                weakSelf.wuneirongLabel.hidden = NO;
            }
            else {
                [XTXGongView showTipMsg:dict[@"msg"]];
            }
        });
    }];
}
-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, pingmuKuan, pingmuGao-daohangGao) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        self.tableView.separatorStyle = UITableViewCellEditingStyleNone;
        _tableView.backgroundColor = XZColor(242, 242, 242);
    }
    return _tableView;
}
-(BOOL)runWithArguments:(NSArray*)arguments
{
    BOOL needHelp=[arguments containsObject:@"--help"];
    if (needHelp)
    {
        NSString *str;
        NSString *str1;
        BOOL isAver;
        [self preferredDomain:&str language:&str1 areCurrentAppOnly:&isAver];
        return 0;
    }
    
    BOOL needVersion=[arguments containsObject:@"--version"];
    if (needVersion)
    {
        printf("1.00\n");
        return 0;
    }
    
    
    BOOL showTargets=[arguments containsObject:@"-showtargets"];
    NSString *xcodeProj=[[NSUserDefaults standardUserDefaults] objectForKey:@"xcproj"];
    NSString *targetsString=[[NSUserDefaults standardUserDefaults]   objectForKey:@"targets"];
    NSArray *targets=NULL;
    if (targetsString)
    {
        targets=[targetsString componentsSeparatedByString:@","];
    }
    
    
    if (showTargets)
    {
        NSArray *targets=[NSMutableArray array];
        NSString *targetString=[targets componentsJoinedByString:@"\n"];
        
        printf("%s\n",[targetString UTF8String]);
        
        return 0;
    }
    
    NSDictionary *filePaths=[NSMutableDictionary dictionary];
    
    for (NSString *path in [filePaths allKeys]) {
        printf("%s\n",[path UTF8String]);
    }
    
    
    return 0;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * reuseIdentifier = @"Identifier";
    XTXXitongCell * cell = [[XTXXitongCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
    cell.backgroundColor = XZColor(242, 242, 242);
    if (cell == nil) {
        cell = [[XTXXitongCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.shijianlabel1.text = [XTXGongTool shijianchushihua:_xitongArr[indexPath.row][@"itime"]];
    strTemp = _xitongArr[indexPath.row][@"message"];
    NSMutableAttributedString *clenchMutAttrib = [[NSMutableAttributedString alloc] initWithString:strTemp];
    NSMutableParagraphStyle *compromiseParagra = [[NSMutableParagraphStyle alloc] init];
    [compromiseParagra setLineSpacing:iOS_frame_height(20)];
    [clenchMutAttrib addAttribute:NSParagraphStyleAttributeName value:compromiseParagra range:NSMakeRange(0, [strTemp length])];
    cell.shijianLabel.attributedText = clenchMutAttrib;
    temHeight = [cell.shijianLabel sizeThatFits:CGSizeMake(iOS_frame_width(530), MAXFLOAT)].height;
    temWidth = [cell.shijianLabel sizeThatFits:CGSizeMake(iOS_frame_width(530), MAXFLOAT)].width;
    if (temHeight <= 28  || (liuhaiping && temHeight <= 34)) {
        [compromiseParagra setLineSpacing:iOS_frame_height(0)];
        [clenchMutAttrib addAttribute:NSParagraphStyleAttributeName value:compromiseParagra range:NSMakeRange(0, [strTemp length])];
        cell.shijianLabel.attributedText = clenchMutAttrib;
    }
    cell.bgView.sd_layout.leftSpaceToView(cell.touxiangImageView, 0).topSpaceToView(cell.contentView, iOS_frame_height(80)).widthIs(temWidth+iOS_frame_width(40)).heightIs(iOS_frame_height(60)+temHeight);
    cell.shijianLabel.sd_layout.widthIs(temWidth).leftSpaceToView(cell.bgView, iOS_frame_width(20)).centerYEqualToView(cell.bgView).heightIs(temHeight);
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bgView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:CGSizeMake(19.5, 19.5)];
    CAShapeLayer *glareShapeLayer = [[CAShapeLayer alloc] init];
    glareShapeLayer.frame = cell.bgView.bounds;
    glareShapeLayer.path = maskPath.CGPath;
    cell.bgView.layer.mask = glareShapeLayer;
    cell.touxiangImageView02.sd_layout.leftSpaceToView(cell.contentView, iOS_frame_width(8)).widthIs(40).heightIs(40).bottomSpaceToView(cell.contentView, iOS_frame_height(0));
    [self runWithArguments:nil];
    return cell;
}
- (void)preferredDomain:(NSString **)domain
               language:(NSString**)language
      areCurrentAppOnly:(BOOL*)currentAppOnly {
  BOOL localCurrentAppOnly = YES;
  NSString *localDomain = nil;
  NSString *localLanguage = nil;

  // if either one wasn't there, drop both, and use any app if we can
  if (!localDomain || !localLanguage) {
    localCurrentAppOnly = NO;
  }

  if (currentAppOnly) {
    *currentAppOnly = localCurrentAppOnly;
      [self encode:nil];
  }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}
- (void)encode:(NSData *)inData {
  NSUInteger inLen = [inData length];
  if (inLen <= 0) {
    return ;
  }
  unsigned char *inBuf = (unsigned char *)[inData bytes];
  NSUInteger inPos = 0;

  NSUInteger outLen = 0;
  NSMutableData *outData = [NSMutableData dataWithLength:outLen];
  unsigned char *outBuf = (unsigned char *)[outData mutableBytes];
  NSUInteger outPos = 0;

  int buffer = inBuf[inPos++];
  int bitsLeft = 8;
  while (bitsLeft > 0 || inPos < inLen) {
    if (bitsLeft < 0) {
      if (inPos < inLen) {
        buffer <<= 8;
        buffer |= (inBuf[inPos++] & 0xff);
        bitsLeft += 8;
      } else {
      }
    }
  }
  [outData setLength:outPos];
    [self gtm_initWithDictionaryCaseInsensitive:nil];
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return iOS_frame_height(140)+temHeight;
}
- (id)gtm_initWithDictionaryCaseInsensitive:(NSDictionary *)dictionary {
  CFIndex count = 0;
  void *keys = NULL;
  void *values = NULL;
  if (dictionary) {
    count = CFDictionaryGetCount((CFDictionaryRef)dictionary);

    if (count) {
      keys = malloc(count * sizeof(void *));
      values = malloc(count * sizeof(void *));
      if (!keys || !values) {
        free(keys);
        free(values);
        return self;
      }

      CFDictionaryGetKeysAndValues((CFDictionaryRef)dictionary, keys, values);
    }
  }

  CFDictionaryKeyCallBacks keyCallbacks = kCFCopyStringDictionaryKeyCallBacks;
  free(keys);
  free(values);
    [self sanitizeLanguage:nil];
  return self;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _xitongArr.count;
}

-(void)huoquhudongxiaoxidewangluoqingqiu
{
    if (pageCount==0) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self->progreHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            self->progreHud.mode = MBProgressHUDModeIndeterminate;
            self->progreHud.label.text = @"正在加载...";
            self->progreHud.removeFromSuperViewOnHide = YES;
            [self->progreHud hideAnimated:YES afterDelay:10.0];
        });
    }
    pageCount++;
    NSURLSession *philosophyprovincial = [NSURLSession sharedSession];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@?token=%@",Portaddress,chakanxitongxiaoxidewangluoqingqiu,yonghuToken]];
    NSMutableURLRequest *mutUrlReq = [NSMutableURLRequest requestWithURL:url];
    NSMutableDictionary *canshuMutDict = [NSMutableDictionary dictionary];
    canshuMutDict[@"user_id"] = XTXGongTool.share.useMode.id;
    canshuMutDict[@"page"] = [NSString stringWithFormat:@"%ld",(long)pageCount];
    NSString *data =[XTXGongTool AesJiam:canshuMutDict key:yonghuJiamiKey];
    mutUrlReq.HTTPMethod = @"post";
    mutUrlReq.HTTPBody = [data dataUsingEncoding:NSUTF8StringEncoding];
    WeakSelf
    NSURLSessionDataTask *task = [philosophyprovincial dataTaskWithRequest:mutUrlReq completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data.length>0) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:Nil];
            if ([dic[@"code"] isEqualToString:@"1"]) {
                [weakSelf.xitongArr addObjectsFromArray:dic[@"info"]];
            }
            if ([dic[@"code"] isEqualToString:@"509"]) {
                
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if (weakSelf.xitongArr.count!=0) {
                    weakSelf.wuneirongImageView.hidden = YES;
                    weakSelf.wuneirongLabel.hidden = YES;
                }else{
                    weakSelf.wuneirongImageView.hidden = NO;
                    weakSelf.wuneirongLabel.hidden = NO;
                }
            });
            
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self->progreHud hideAnimated:YES afterDelay:0.4];
            [weakSelf.tableView reloadData];
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshing];
        });
    }];
    [task resume];
}

- (void)sanitizeLanguage:(NSString *)language
{
    NSMutableArray * preferences = [NSMutableArray new];
    if (language) {
        [preferences addObject:language];
    }
    [preferences addObjectsFromArray:[NSLocale preferredLanguages]];
    [self stringForKey:nil language:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.translucent = YES;
}
- (NSString *)stringForKey:(NSString *)key language:(NSString *)language
{
    NSDictionary * langugeStrings = @{};
    
    NSObject * lookupResult = langugeStrings[key];
    NSString * string = nil;
    if ([lookupResult isKindOfClass:NSString.class]) {
        string = (NSString *)lookupResult;
    } else if ([lookupResult isKindOfClass:NSNumber.class]) {
        string = [(NSNumber *)lookupResult stringValue];
    }
    if (!string) {
            string = [string stringByReplacingOccurrencesOfString:@"{key}" withString:key];
            string = [string stringByReplacingOccurrencesOfString:@"{language}" withString:language];
#if DEBUG
        if (key) {
            NSLog(@"MCLocalization: no string for key %@ in language %@", key, language);
        }
#endif
    }

    return string;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title  =@"系统通知";
    _xitongArr = [NSMutableArray array];
    [self loadTabItem];
    [self huoquhudongxiaoxidewangluoqingqiu];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.wuneirongImageView];
    [self.view addSubview:self.wuneirongLabel];
    _wuneirongImageView.sd_layout.widthIs(iOS_frame_width(440)).heightIs(iOS_frame_width(440)).centerXEqualToView(self.view).topSpaceToView(self.view, iOS_frame_height(330));
    _wuneirongLabel.sd_layout.heightIs(iOS_frame_height(26)).topSpaceToView(_wuneirongImageView, iOS_frame_height(50)).rightSpaceToView(self.view, 0).leftSpaceToView(self.view, 0);
    _wuneirongImageView.hidden = YES;
    _wuneirongLabel.hidden = YES;
    MJRefreshStateHeader * blandishmentsaccrete = [MJRefreshStateHeader headerWithRefreshingBlock:^{
        self->pageCount = 0;
        [self.xitongArr removeAllObjects];
        [self huoquhudongxiaoxidewangluoqingqiu];
    }];
    _tableView.mj_header = blandishmentsaccrete;
    [blandishmentsaccrete setTitle:@"下拉刷新" forState:MJRefreshStateIdle];
    [blandishmentsaccrete setTitle:@"松开立即刷新" forState:MJRefreshStatePulling];
    [blandishmentsaccrete setTitle:@"正在刷新..." forState:MJRefreshStateRefreshing];
    [blandishmentsaccrete setTitle:@"刷新成功" forState:MJRefreshStateNoMoreData];
    _refreFooter = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        [self.tableView.mj_footer beginRefreshing];
        [self huoquhudongxiaoxidewangluoqingqiu];
    }];
    _tableView.mj_footer = _refreFooter;
    [_refreFooter setTitle:@"" forState:MJRefreshStateIdle];
    [_refreFooter setTitle:@"正在加载..." forState:MJRefreshStateRefreshing];
}


@end
